package com.supreme.studyserver.service;

import com.supreme.studyserver.annotation.MissingYou;
import com.supreme.studyserver.entity.School;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Service
public class ReflectService {

    public School demoOne() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
        final School school = new School();

        final Class<School> schoolClass = School.class;
        final Method setNameMethod = schoolClass.getMethod("setName", String.class);
        setNameMethod.invoke(school, "大连理工大学");

        System.out.println(school.getName());

        final Field nameField = schoolClass.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(school, "大连工业大学");
        System.out.println(nameField.get(school));

        return school;
    }

    @MissingYou
    public School demoTwo() {
        final String threadName = Thread.currentThread().getName();
        System.out.println("demoTow: " + threadName);

        final School school = new School();
        final Class<School> schoolClazz = School.class;

        final Method setNameMethod = ReflectionUtils.findMethod(schoolClazz, "setName", String.class);
        assert setNameMethod != null;
        ReflectionUtils.invokeMethod(setNameMethod, school, "大连海洋大学");

        System.out.println(school.getName());

        return school;
    }

    @MissingYou
    public String demoException(Boolean enableException) {
        if (enableException) {
            throw new RuntimeException("enable exception");
        }

        return "success return";
    }

    @MissingYou(value = "辽宁师范大学")
    public School demoAnnoSchool(String name) {
        final School school = new School();
        school.setName(name);
        return school;
    }
}
